package com.flink.flinkdemo.demo;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author zhangy on 2020/12/27
 * @description: add you description
 *
 * 流式计算均值
 *
 * 在flatMap时要加入次数关键值  所以用Tuper3,或者 Tuper4(key,cunt,sum,avg)
 */
public class StreamCountAvgDealTime {


    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> text = env.socketTextStream("localhost", 9001, "\n");
        SingleOutputStreamOperator<Tuple3<String, Integer, Double>> operator = text.flatMap(new FlatMapFunction<String, Tuple3<String, Integer, Double>>() {
            @Override
            public void flatMap(String value, Collector<Tuple3<String, Integer, Double>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    String[] wordSplit = word.split(":");
                    out.collect(new Tuple3<>(wordSplit[0], 1, Double.valueOf(wordSplit[1])));
                }
            }
        });
        SingleOutputStreamOperator<Tuple3<String, Integer, Double>> reduce = operator.keyBy(0).reduce(new ReduceFunction<Tuple3<String, Integer, Double>>() {
            @Override
            public Tuple3<String, Integer, Double> reduce(Tuple3<String, Integer, Double> value1, Tuple3<String, Integer, Double> value2) throws Exception {
                return new Tuple3<>(value1.f0, value1.f1 + 1, Double.valueOf((value2.f2 + value1.f2)/(value1.f1 + 1)));
            }
        });


        reduce.print();
        env.execute();


    }
}